<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class Admin_Controller extends MX_Controller{

	protected $controller = '';
	protected $is_main_controller = false;
	protected $is_special_action = false;
	protected $module = '';
	protected $module_id = 0;
	protected $module_name = 0;
	
	// Config table
	protected $table;
	protected $table_suffix;
	
	// Config List view
	protected $list_view_condition = '';
	protected $list_view_order_name = 'created';
	protected $list_view_order_direction = 'DESC';
	protected $list_view_status_show = true;
	protected $status_name = 'status';
	protected $list_view_created_show = true;
	protected $list_view_created_name = 'created'; // Not used
	protected $list_view_num_links = 3;
	protected $list_view_pagination = array(10,25,50,100);
	protected $list_view_searched_fields = array();
	protected $list_view_fields = array();
	protected $list_search_filter = array();
	// Config Form view
	protected $form_view_fields = array();
	
	// Config All columns/fields
	protected $fields = array();
	
	function __construct(){
		parent::__construct();
		$this->load->helper('main_helper');
		$this->load->helper('admin_helper');
		
		// Get controller
		$current_class = get_class($this);
		$controller = strtolower($current_class);
		// Get module (Normally module = controller -> No need to config module)
		$this->module = !empty($this->module) ? $this->module : $controller;
		$data['module'] = $this->module;
		
		// Config model
		$this->load->model($this->module.'_model','model');
		$this->model->module = $this->module;
		// Get table (Normally table_suffix = module -> No need to config table_suffix/table)
		$this->table_suffix = !empty($this->table_suffix) ? $this->table_suffix : $this->module;
		$this->table = !empty($this->table) ? $this->table : PREFIX.$this->table_suffix;
		$this->model->table = !empty($this->model->table) ? $this->model->table : $this->table;
		$this->model->status_name = !empty($this->model->status_name) ? $this->model->status_name : $this->status_name;
			
		if($this->uri->segment(1)=='admincp' && !$this->is_special_action){
			if(!$this->session->userdata('userInfo')){
				header('Location: '.PATH_URL.'admincp/login');
				return false;
			}
			
			// Check existing module
			$this->load->model('manager_modules/manager_modules_model');
			$get_module = $this->manager_modules_model->check_modules($this->module);
			if(!empty($get_module)){
				$this->module_id = $get_module[0]->id;
				$this->module_name = $get_module[0]->name;
			}
			
			// Get permission
			$this->load->model('admincp/admincp_model');
			$info = $this->admincp_model->getInfo($this->session->userdata('userInfo'));
			if(!empty($info[0])){
				$_SESSION['user_permission'] = $info[0]->permission;
			}
			$get_name_module = $this->manager_modules_model->check_modules($this->module);
			
			// Get config of List view and Form view
			$this->process_fields();
			$this->model->list_view_condition = $this->list_view_condition;
			$this->model->list_view_searched_fields = $this->list_view_searched_fields;
			$this->model->form_view_fields = $this->form_view_fields;
			$this->model->list_view_searched_filter = $this->list_search_filter;
			
			$this->load->vars($data);
			$this->template->set_template('admin');
			$this->template->write('title','Admin Control Panel');
		}
	}
	
	public function admincp_index(){
		admin_check_permission($this->module_id,'r',true);
		$get_name_module[0]=array();
		$get_name_module = $this->manager_modules_model->check_modules($this->module);
		$pagination_links = $this->admincp_get_pagination_links($this->input->post('start'),$this->list_view_pagination[0]);
		$data = array(
			'get_name_module'=>$get_name_module[0],
			'start' => $this->input->post('start'),
			'per_page' => $this->input->post('per_page'),
			'module_name'=>$this->module_name,
			'module' => $this->module,
			'list_view_order_name' => $this->list_view_order_name,
			'list_view_order_direction' => $this->list_view_order_direction,
			'search_field' => $this->list_view_searched_fields,
			'list_view_pagination' => $this->list_view_pagination,
			'search_filter'	=>	$this->list_search_filter,
			'pagination_links'=> $pagination_links

		);
	
		//Ajax search filter data
		if(!empty($this->list_search_filter)){
			$list_data = $this->model->fetch('*', $this->list_search_filter['data_table']);
			if(isset($this->list_search_filter['multi_level'])){
				$data['search_filter']['list_data'] = admin_get_multi_level_select($list_data, 0, $this->list_search_filter['multi_level']['parent_id_field_name'],$this->list_search_filter['multi_level']['parent_title_field_name']);
			}
			else{
				$data['search_filter']['list_data'] = admin_get_select_options($list_data, $data['search_filter']['parent_text']);
			}
			if(isset($data['search_filter']['sub_filter'])){
				$sub_list_data = $this->model->fetch('*', $this->list_search_filter['sub_filter']['data_table']);
				if(isset($this->list_search_filter['sub_filter']['multi_level'])){
					$data['search_filter']['sub_filter']['list_data'] = admin_get_multi_level_select($sub_list_data, 0, $this->list_search_filter['sub_filter']['multi_level']['parent_id_field_name'],$this->list_search_filter['sub_filter']['multi_level']['parent_title_field_name']);
				}
				else{
					$data['search_filter']['sub_filter']['list_data'] = admin_get_select_options($sub_list_data, $data['search_filter']['sub_filter']['parent_text']);
				}
			}
		}
		$this->session->set_userdata('start', $this->input->post('start'));
		$this->template->write_view('content','BACKEND/index',$data);
		$this->template->render();	
	}
	public function admincp_get_pagination_links($star = '', $per = '')
	{
		admin_check_permission($this->module_id,'w',true);
		$flag = FALSE;
		if($star == '' && $per == ''){
			$star = $this->input->post('start');
			$per = $this->input->post('per_page');
			$flag = TRUE;
		}
		$this->load->library('AdminPagination');
		$config['total_rows'] = $this->model->getTotalContent();
		$config['per_page'] = $per;
		$config['num_links'] = $this->list_view_num_links;
		$config['func_ajax'] = 'updatePagination';
		$config['start'] = $star;
		$this->adminpagination->initialize($config);
		if($flag){
			echo $this->adminpagination->create_links();
		} else {
			return $this->adminpagination->create_links();
		}
	}
	
	public function admincp_update($id=0){
		admin_check_permission($this->module_id,'w',true);
		$get_name_module[0]=array();
		$get_name_module = $this->manager_modules_model->check_modules($this->module);
		if($this->module == 'accounts'){
			if($id==1){
				if($this->session->userdata('userInfo')!='root'){
					header('Location:'.PATH_URL.'admincp/permission');
				}
			}
		}
		admin_check_permission($this->module_id,'r',true);
		$result = array();
		if($id!=0){
			$result = $this->model->getDetailManagement($id);
		}

		foreach($this->form_view_fields as $k=>$form_view_config){
			$form_view_config['html'] = $this->form_field_build_field($form_view_config,$result, $id);
			$this->form_view_fields[$k] = $form_view_config;
		}
		$data = array(
			'get_name_module'=>$get_name_module[0],
			'result'=>$result,
			'module'=>$this->module,
			'id'=>$id,
			'form_view_fields' => $this->form_view_fields
		);
		if($this->module == 'accounts'){
			$this->load->model('account_groups/account_groups_model');
			$list_group = $this->account_groups_model->list_groups();
			$data['list_group'] = $list_group;
		}
		// pr($this->form_view_fields,1);
		$this->template->write_view('content','BACKEND/ajax_editContent',$data);
		$this->template->render();
	}
	
	public function admincp_save(){
		admin_check_permission($this->module_id,'w',true);
		if($_POST){
			$data = modules::run($this->module.'/admincp_saveAction');
			$new_id = $this->model->saveManagement($data);
			$this->after_save($new_id);
			if ($new_id) {
				// After saving				
				if(!empty($data['FILES'])){
					if($data['FILES']['fileName'] != FALSE){
						if($_FILES){
							foreach($data['FILES']['fileName'] as $k=>$v){
								if(isset($_FILES['fileAdmincp']['error'][$k])){
									$upload_path = BASEFOLDER.'static/uploads/'.$this->module.'/'.$data['FILES']['fileOption'][$k].'/';
									if (!file_exists($upload_path))
									{
										mkdir($upload_path);
									}
									move_uploaded_file($data['FILES']['tmp_name'][$k], $upload_path.$data['FILES']['fileName'][$k]);
								}
							}
						}
					}
				}
				print 'success';
				exit;
			}
		}
	}
	
	protected function after_save($obj_id){
		// For doing after saving
	}
	
	public function admincp_delete(){
		admin_check_permission($this->module_id,'d',true);
		$id = (int)$this->input->post('id');
		if($id){
			// Before delete
			$this->before_delete($id);
			
			$result = $this->model->getDetailManagement($id);
			modules::run('admincp/saveLog',$this->module,$id,'delete','delete');
			$this->db->where('id',$id);
			if($this->db->delete($this->table)){
				//Xóa hình khi Delete				
				$listUploadField = $this->model->getVarModel('listUploadField');
				foreach($listUploadField as $k => $v){
					if( isset($result->$k) && $result->$k != ''){
						@unlink(BASEFOLDER.'static/uploads/'.$this->module.'/'.$v.'/'.$result->$k);
					}
				}
				
				
				
				return true;
			}
		}
	}
	
	protected function before_delete($obj_id){
		// For doing after deleting
	}
	
	
	public function admincp_ajaxLoadContent() {
		$this->load->library('AdminPagination');
		$config['total_rows'] = $this->model->getTotalsearchContent($this->input->post('search_field'));
		$config['per_page'] = $this->input->post('per_page');
		$config['num_links'] = $this->list_view_num_links;
		$config['func_ajax'] = 'searchContent';
		$config['start'] = $this->input->post('start');
		$this->adminpagination->initialize($config);
		if($this->module=='manager_modules'){
			$read_dir = scandir(BASEFOLDER.'application/modules');
			foreach($read_dir as $v){
				if($v!='.' && $v!='..' && $v!='home' && $v!='admincp'){
					if(!$this->model->check_modules($v)){
						$data_module = array(
							'name'=>ucfirst(str_replace('_',' ',$v)),
							'name_function'=>$v,
							$this->status_name=>0,
							'created'=>date('Y-m-d H:i:s')
						);
						$this->db->insert($this->table,$data_module);
					}
				}
			}
		}
		
		$result = $this->model->getsearchContent($config['per_page'], $this->input->post('start'), $this->input->post('search_field'));
		$data = array(
			'result' => $result,
			'per_page' => $this->input->post('per_page'),
			'start' => $this->input->post('start'),
			'module' => $this->module,
			'search_field' => $this->input->post('list_view_searched_fields'),
			'list_view_status_show' => $this->list_view_status_show,
			'status_name' => $this->status_name,
			'list_view_created_show' => $this->list_view_created_show,
			'list_view_fields' => $this->list_view_fields,
			'controller'=>$this,
			'list_view_pagination' => $this->list_view_pagination
		);
		$this->session->set_userdata('start', $this->input->post('start'));
		$this->load->view('BACKEND/ajax_loadContent', $data);
	}
	
	protected function process_fields(){
		$this->_process_fields_for_view('list_view');
		$this->_process_fields_for_view('form_view');
		
		if(!empty($this->list_view_fields)){
			foreach($this->list_view_fields as $k => $field_config){
				$field_config['key'] = !empty($field_config['key']) ? $field_config['key'] : $k;
				$this->list_view_fields[$k] = $field_config;
			}
		}
		if(!empty($this->form_view_fields)){
			foreach($this->form_view_fields as $k => $field_config){
				$field_config['key'] = !empty($field_config['key']) ? $field_config['key'] : $k;
				$field_config['name'] = !empty($field_config['name']) ? $field_config['name'] : $field_config['key'];
				$this->form_view_fields[$k] = $field_config;
			}
		}
	}
	private function _process_fields_for_view($view){
		$is_empty_view_fields = false;
		switch($view){
			case 'list_view':
				$view_fields = &$this->list_view_fields; // Pointer
				break;
			case 'form_view':
				$view_fields = &$this->form_view_fields; // Pointer
				break;
		}
		if(empty($view_fields)){
			$is_empty_view_fields = true;
			$view_fields = array();
		}
		
		if($is_empty_view_fields && !empty($this->fields)){
			foreach($this->fields as $k => $field_config){
				if(isset($field_config[$view])){ // If having config 'list_view' or 'form_view' => Copy into $view_fields
					// Copy
					$view_field_config = $field_config[$view];
					// Clear
					unset($field_config['list_view']);
					unset($field_config['form_view']);
					
					if(!empty($view_field_config['text'])){
						unset($field_config['text']);
					}
					$view_field_config = array_merge($field_config,$view_field_config);
					
					$view_field_config['key'] = $k;
					$view_fields[$k] = $view_field_config;
				}
			}
		}
	}
	
	function form_field_build_field($form_view_config,$obj, $id = 0){
		admin_check_permission($this->module_id,'w',true);
		$html = '';
		$data['form_view_config'] = $form_view_config;
		$data['result'] = $obj;
		$data['id'] = $id;
		
		switch($form_view_config['type']){
			case 'text':
			case 'password':
				$html = $this->load->view('BACKEND/form_view/text_and_password', $data, true);
				break;
			
			case 'textarea':
				$html = $this->load->view('BACKEND/form_view/textarea', $data, true);
				break;
			
			case 'checkbox':
				$html = $this->load->view('BACKEND/form_view/checkbox', $data, true);
				break;
			
			case 'select':
				$this->load->helper('admin_helper');
				if(!empty($form_view_config['select_config'])){
					$select_config = $form_view_config['select_config'];
					$select_config['referred_condition'] = !empty($select_config['referred_condition']) ? $select_config['referred_condition'] : '';
					$parent_list = $this->model->fetch('*', $select_config['referred_table_name'], $select_config['referred_condition']);
					if(!empty($select_config['multi_level_config'])){
						$multi_level_config = $select_config['multi_level_config'];
						$data['select_options'] = admin_get_multi_level_select($parent_list, $parent_id = 0, $multi_level_config['parent_id_field_name'], $multi_level_config['parent_title_field_name']);
					} else {
						$data['select_options'] = $parent_list;
					}
					$data['CI'] = $this;
					$html = $this->load->view('BACKEND/form_view/select', $data, true);
				}
				break;
			
			case 'file':
				$html = $this->load->view('BACKEND/form_view/file', $data, true);
				break;
			
			case 'radio':
				// load_radio_view
				break;
			
			case 'gallery':
				$html = $this->load->view('BACKEND/form_view/gallery', $data, true);
				break;
			
		}
		
		
		//load custom view
		return $html;
	}
	
	public function admincp_ajaxUpdateStatus(){
		if(!admin_check_permission($this->module_id,'w')){
			print '<script type="text/javascript">show_perm_denied()</script>';
			$status = $this->input->post('status');
			$data = array(
				$this->status_name => $status
			);
		} else {
			if($this->input->post('status')==0){
				$status = 1;
			}else{
				$status = 0;
			}
			$data = array(
				$this->status_name => $status
			);
			modules::run('admincp/saveLog',$this->module,$this->input->post('id'),'status','update',$this->input->post('status'),$status);
			$this->db->where('id', $this->input->post('id'));
			$this->db->update($this->table, $data);
		}
		
		$update = array(
			'status'=>$status,
			'id'=>$this->input->post('id'),
			'module'=>$this->module
		);
		$this->load->view('BACKEND/ajax_updateStatus',$update);
	
	}
	
	function admincp_uploadFiles(){
		$fileName = '';
		$fileOption = '';
		$tmp_name = '';
		if(count($_FILES) > 0 ){
			
			$fileOption = $this->model->getVarModel('listUploadField');
			// pr($fileOption);
			foreach ($_FILES['fileAdmincp']['name'] as $key	=>	$value ){
				$fileName[$key]	=	'';
			}
			//

			foreach($fileName as $k=>$v){
				if(isset($_FILES['fileAdmincp']['error'][$k])){
					$typeFile = explode('/',$_FILES['fileAdmincp']['type'][$k]);
					// pr($typeFile);
					if($typeFile[0] == 'image' && $typeFile[0] == $fileOption[$k]){
						$tmp_name[$k] = $_FILES['fileAdmincp']["tmp_name"][$k];
						$file_name[$k] = $_FILES['fileAdmincp']['name'][$k];
						$ext = strtolower(substr($file_name[$k], -4, 4));
						if($ext=='jpeg'){
							$fileName[$k] = time().'_'.SEO(substr($file_name[$k],0,-5)).'.jpg';
						}else{
							$fileName[$k] = time().'_'.SEO(substr($file_name[$k],0,-4)).$ext;
						}
					}elseif($typeFile[0] == 'audio' && $typeFile[0] == $fileOption[$k] ){
						$tmp_name[$k] = $_FILES['fileAdmincp']["tmp_name"][$k];
						$file_name[$k] = $_FILES['fileAdmincp']['name'][$k];
						$ext = strtolower(substr($file_name[$k], -3, 3));
						if($ext != 'mp3'){
							print 'Audio file extension not support';
							exit;
						}else{
							$fileName[$k] = time().'_'.SEO(substr($file_name[$k],0,-4)).'.mp3';
						}
					}
					elseif($typeFile[0] == 'video' && $typeFile[0] == $fileOption[$k] ){
						$tmp_name[$k] = $_FILES['fileAdmincp']["tmp_name"][$k];
						$file_name[$k] = $_FILES['fileAdmincp']['name'][$k];
						$ext = strtolower(substr($file_name[$k], -3, 3));
						if($ext != 'flv' && $ext != 'mp4'){
							print 'Video file extension not support';
							exit;
						}else{
							$fileName[$k] = time().'_'.SEO(substr($file_name[$k],0,-4)).'.'.$ext;
						}
					}
					else{
						print 'File extension not support';
						exit;
					}

				}
			}
			
		}
		$data = array(
				'fileName'	=>	$fileName,
				'fileOption'	=>	$fileOption,
				'tmp_name'	=>	$tmp_name
			);
		return $data;
	}
	
	public function ajax_get_sub_select(){
		$sub_select_config = $this->input->post();
		$parent_id = (int)$this->input->post('value');
		$data = admin_build_sub_select_config($sub_select_config,$parent_id);
		echo $this->form_field_build_field($data,'');
	}
	
	public function ajaxGetFilter(){
		$data = $this->input->post();
		if($data['value'] == 'all')
			$condition = '';
		else	
			$condition = $data['condition'] . ' = ' . $data['value'];
		$list_data = $this->model->fetch('*', $data['data_table'], $condition);
		$options = '<option value="all">'.$data['default_parent_text'].'</option>';
		foreach($list_data as $k=>$v)
			$options .= '<option value="'.$v->id.'">'.$v->$data['parent_text'].'</option>';
		echo $options;
	}
		/*------------------------------------ Admin GALLERY ------------------------------------*/
	
	public function admincp_uploader($category_id=0, $key = ''){
		if($category_id!=0 && $key !='' ){
			$table = $this->form_view_fields[$key]['table'];
			header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
			header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
			header("Cache-Control: no-store, no-cache, must-revalidate");
			header("Cache-Control: post-check=0, pre-check=0", FALSE);
			header("Pragma: no-cache");

			// Settings
			$targetDir = BASEFOLDER.'static/uploads/'.$this->module.'/';
			@set_time_limit(5 * 60);

			// Get parameters
			$chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
			$chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
			$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';

			// Clean the fileName for security reasons
			$fileName = preg_replace('/[^\w\._]+/', '', $fileName);

			// Make sure the fileName is unique but only if chunking is disabled
			if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
				$ext = strrpos($fileName, '.');
				$fileName_a = substr($fileName, 0, $ext);
				$fileName_b = substr($fileName, $ext);

				$count = 1;
				while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
					$count++;

				$fileName = $fileName_a . '_' . $count . $fileName_b;
			}
			
			//Code make folder
			check_dir_upload($targetDir);

			$ext = strtolower(substr($fileName, -4, 4));
			if($ext=='jpeg'){
				$fileName = date('Y').'/'.date('m').'/'.date('d').'/'.time().'_'.SEO(substr($_FILES['file']['name'],0,-5)).'.jpg';
			}else{
				$fileName = date('Y').'/'.date('m').'/'.date('d').'/'.time().'_'.SEO(substr($_FILES['file']['name'],0,-4)).$ext;
			}

			// Look for the content type header
			if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
				$contentType = $_SERVER["HTTP_CONTENT_TYPE"];

			if (isset($_SERVER["CONTENT_TYPE"]))
				$contentType = $_SERVER["CONTENT_TYPE"];


			// Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
			if (strpos($contentType, "multipart") !== FALSE) {
				if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
					// Open temp file
					$out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
					if ($out) {
						// Read binary input stream and append it to temp file
						$in = fopen($_FILES['file']['tmp_name'], "rb");

						if ($in) {
							while ($buff = fread($in, 4096))
								fwrite($out, $buff);
						} else
							die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
						fclose($in);
						fclose($out);
						@unlink($_FILES['file']['tmp_name']);
						$data = array(
							'category_id'=>$category_id,
							'image'=>$fileName,
							$this->status_name=>1,
							'created'=>date('Y-m-d H:i:s',time())
						);
						if($this->db->insert(PREFIX.$table,$data)){
							modules::run('admincp/saveLog',$this->module,$this->db->insert_id(),'Add new','Add new','',$fileName);
						}
					} else
						die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
				} else
					die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
			} else {
				// Open temp file
				$out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
				if ($out) {
					// Read binary input stream and append it to temp file
					$in = fopen("php://input", "rb");

					if ($in) {
						while ($buff = fread($in, 4096))
							fwrite($out, $buff);
					} else
						die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');

					fclose($in);
					fclose($out);
				} else
					die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
			}

			// Return JSON-RPC response
			//die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
		}
	}
	
	
	public function admincp_list_image_of_gallery($category_id, $key = ''){
		$table = $this->form_view_fields[$key]['table'];
		$data['list_image'] = $this->model->getListImageOfGallery($category_id, $table);
		$this->load->view('BACKEND/form_view/ajax_list_image_of_gallery',$data);
	}
	
	public function admincp_deleteImageGallery($key = ''){
		admin_check_permission($this->module_id,'d',true);
		if($this->input->post('id') && $key !=''){
			$table = $this->form_view_fields[$key]['table'];
			$id = $this->input->post('id');
			$result = $this->model->getDetailImageOfGallery($id, $table);
			modules::run('admincp/saveLog',$this->module,$id,'Delete','Delete');
			$this->db->where('id',$id);
			if($this->db->delete(PREFIX.$table)){
				//Xóa hình khi Delete
				@unlink('static/uploads/'.$this->module.'/'.$result->image);
				return true;
			}
		}
	}
	
	/*------------------------------------ End Admin GALLERY ------------------------------------*/
}